package config

import (
	"github.com/spf13/viper"
)

var (
	defaultName       = "config"
	defaultConfigType = "yaml"
	defaultPath       = "."
)

func Default() {
	//引入viper配置文件
	viper.SetConfigName(defaultName) //defaultName := lib.AppName()
	viper.SetConfigType(defaultConfigType)
	viper.AddConfigPath(defaultPath)
}

func SetConfigInfo(name, suffix, path string) {
	viper.SetConfigName(name) //defaultName := lib.AppName()
	viper.SetConfigType(suffix)
	viper.AddConfigPath(path)
}

func Load() error {
	return viper.ReadInConfig()
}

func Store() error {
	err := viper.SafeWriteConfig()
	if err != nil {
		err = viper.WriteConfig()
	}
	return err
}

func Register(module string, key string, value any) {
	viper.SetDefault(module+"."+key, value)
}

func GetBool(module string, key string) bool {
	return viper.GetBool(module + "." + key)
}

func GetString(module string, key string) string {
	return viper.GetString(module + "." + key)
}

func GetInt(module string, key string) int {
	return viper.GetInt(module + "." + key)
}

func GetFloat(module string, key string) float64 {
	return viper.GetFloat64(module + "." + key)
}

func GetStringSlice(module string, key string) []string {
	return viper.GetStringSlice(module + "." + key)
}

func Set(module, key string, value any) {
	viper.Set(module+"."+key, value)
}

func Unmarshal(value any, arr ...string) error {
	key := ""

	for _, s := range arr {
		if len(key) != 0 {
			key += "."
		}
		key += s
	}
	if len(key) != 0 {
		return viper.UnmarshalKey(key, value)
	} else {
		return viper.Unmarshal(value)
	}
}

func ReadConfigAndFileExist() (bool, error) {
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// 配置文件未找到
			return false, nil
		} else {
			// 其他错误
			return true, err
		}
	}
	return true, nil
}
